# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import Http404

from blog.models import Post, Category

def index(request):
    '''blog 列表'''

    posts = Post.objects.all()
    categories = Category.objects.all()
    return render_to_response("blog/index.html",
                              {"posts": posts,
                                "categories": categories,
                              },
                             context_instance=RequestContext(request))

def post(request, pk):
    '''单篇文章'''

    post = get_object_or_404(Post, pk=pk)
    return render_to_response("blog/post.html", 
                              {"post":post},
                              context_instance=RequestContext(request))

def category(request, pk):
    """相应分类下文章的检索"""

    try:
        cate = Category.objects.get(pk=pk)
    except Category.DoesNotExist:
        raise Http404
    
    posts = cate.post_set.all() # 获取分类下的所有文章
    return render_to_response('blog/index.html', 
                              {'posts': posts, 
                                'is_category': True,
                                'cate_name': cate.name,
                                'categories': Category.objects.all()},
                             context_instance=RequestContext(request))
